package com.huixiong.nio.channel.socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;

/**
 * <描述>
 *
 * @author timothy.yang cloudwise
 * @since 2022-05-08 20:40
 */
public class ServerSocketChannelDemo {
    public static void main(String[] args) throws IOException, InterruptedException {
        int port = 8888;

        ByteBuffer buffer = ByteBuffer.wrap("hello world".getBytes(StandardCharsets.UTF_8));

        ServerSocketChannel channel = ServerSocketChannel.open();

        channel.configureBlocking(false);

        channel.socket().bind(new InetSocketAddress(port));

        while (true) {
            SocketChannel client = channel.accept();
            if(client == null){
                System.out.println("没有连接");
                Thread.sleep(2000);
            } else {
                client.write(buffer);
                System.out.println(client.getLocalAddress());
            }
        }
    }
}
